import { publicRoutes } from '../../router/index'
const viewsModules = import.meta.glob('@/views/**/*')
const layoutModules = import.meta.glob('@/layout/**/*')
export default {
  namespaced: true,
  state: () => ({
    // 路由表: 初始时所拥有的路由表
    routes: []
  }),
  mutations: {
    /**
     * 增加路由
     */
    setRoutes(state: any, newRoutes: any) {
      state.routes = [...publicRoutes, ...newRoutes]
    }
  },
  actions: {
    /**
     *  动态生成私有路由表
     */
    generateRoutes({ commit }: any, menu: []) {
      const routes = <any>[]
      if (menu) {
        menu.forEach((item: any) => {
          const { path, redirect, name, icon, component, children, title } = item
          if (path) {
            const childrenRoute = <any>[]
            if (
              children &&
              children instanceof Array &&
              children.length > 0
            ) {
              item.children.forEach((route: any) => {
                if (route.path.indexOf(':') !== -1) {
                  const childRoute = {
                    // 格式化之后的数据赋值
                    path: route.path,
                    name: route.name,
                    component: viewsModules[`/src/${route.component}/index.vue`],
                    props: true,
                    meta: {
                      icon: route.icon,
                      title: route.title
                    }
                  }
                  childrenRoute.push(childRoute)
                } else {
                  const childRoute = {
                    // 格式化之后的数据赋值
                    path: route.path,
                    name: route.name,
                    component: viewsModules[`/src/${route.component}/index.vue`],
                    meta: {
                      icon: route.icon,
                      title: route.title
                    }
                  }
                  childrenRoute.push(childRoute)
                }
              })
              const route = {
                // 格式化之后的数据赋值
                path: path,
                name: name,
                redirect: redirect,
                component: layoutModules[`/src/${component}/index.vue`],
                meta: {
                  icon: icon,
                  title: title
                },
                children: childrenRoute
              }
              routes.push(route)
            }
          }
        })
      }
      routes.push(
        // 所有不匹配的路由,全部进入404 的路由配置
        // 注意: 该配置必须要在所有路由指定之后
        {
          path: '/:catchAll(.*)',
          redirect: '/404'
        }
      )
      commit('setRoutes', routes)
      return routes
    }
  }
}
